<template>
  <div class="order-container">
    <div class="order-headbox">
      <span>订单</span>
    </div>

    <div class="order-menu-box">
      <van-tabs v-model="activeName">
        <van-tab title="未完成订单" name="a"></van-tab>
        <van-tab title="历史订单" name="b"></van-tab>
        <van-tab title="取消的订单" name="c"></van-tab>
      </van-tabs>
    </div>

    <div class="order-data-box" v-if="activeName === 'b'">
      <van-sticky :offset-top="46">
        <van-tabs v-model="dateIndex">
          <van-tab v-for="(item, i) in dateList" :title="item" :key="i"> </van-tab>
        </van-tabs>
      </van-sticky>
    </div>
    <div class="history-box" v-for="item in sortHistoryList" :key="item.id">
      <div class="history-content">
        <div class="order-state">
          <div class="order-date">
            <span>{{ item.status }} {{ item.invoice.datetime_close }}</span>
          </div>
          <div class="order-share">
            <van-icon name="share-o" />
            <span>分享</span>
          </div>
        </div>
        <div class="order-content" @click="viewDetail(item)">
          <div class="order-img">
            <div class="img-list" v-for="img in item.invoice.invoice_line" :key="img.id">
              <img :src="img.item.image_thumbnail_cdn === null || img.item.image_thumbnail_cdn === undefined ? localIMG : img.item.image_thumbnail_cdn" alt="img" @error="handleError($event)" />
            </div>
          </div>
        </div>
        <div class="order-amount">
          <span>￥{{ item.grand_total }}</span>
          <span>X {{ item.invoice.invoice_line[0].quantity }}件</span>
        </div>
      </div>
    </div>
    <van-empty description="暂无订单" v-if="sortHistoryList.length === 0" />

    <div class="bottom-box"></div>
  </div>
</template>

<script>
import moment from 'moment-timezone'

export default {
  data() {
    return {
      activeName: 'b',
      dateList: ['今天', '过去7天', '过去30天', '2021', '2020', '2019', '2018'],
      dateIndex: 0,
      historyOrderList: [],
      nowOrderDetail: {},
      localIMG: './../static/img/mxbc/Ice_Cream/Ferris_Crispy.jpeg'
    }
  },
  created() {
    var query = this.$route.query
    if (query.dateIndex) {
      this.activeName = this.$route.query.activeName
      this.dateIndex = Number(this.$route.query.dateIndex)
    }
    // 初始化时区
    var TimeZone = moment.tz.guess()
    // 初始化历史订单列表
    if (this.$store.state.historyOrderList.data === undefined) {
      this.$store.dispatch('getHistoryOrder')
    }
    this.$toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 120
    })
    setTimeout(() => {
      this.historyOrderList = this.$store.state.historyOrderList.data
      var arr = this.historyOrderList
      arr.forEach((item, i) => {
        // 换算当前时区时间
        const datetimeClose = moment(new Date(item.invoice.datetime_close)).tz(TimeZone)
        const createdAt = moment(new Date(item.invoice.datetime_close)).tz(TimeZone)
        arr[i].invoice.datetime_close = datetimeClose.format('YYYY-MM-DD kk:mm:ss').replace(/([ ][24]+)/g, ' 00')
        arr[i].created_at = createdAt.format('YYYY-MM-DD kk:mm:ss').replace(/([ ][24]+)/g, ' 00')
        this.historyOrderList = arr
      })
    }, 120)
  },
  computed: {
    // 计算属性分类订单日期和类型
    sortHistoryList() {
      var viewType = this.activeName
      var list = this.historyOrderList
      var date = this.dateList[this.dateIndex]
      var timer = 0
      var dateList = []
      // 分类时间
      switch (date) {
        case '今天':
          timer = new Date().getDate()
          dateList = list.filter(x => new Date(x.invoice.datetime_close).getDate() === timer)
          break
        case '过去7天':
          timer = moment(new Date(Date.parse(new Date()) - 7 * 24 * 60 * 60 * 1000))
            .format('YYYY-MM-DD kk:mm:ss')
            .replace(/([ ][24]+)/g, ' 00')
          dateList = list.filter(x => new Date(Date.parse(new Date())) <= timer)
          break
        case '过去30天':
          timer = moment(new Date(Date.parse(new Date()) - 30 * 24 * 60 * 60 * 1000))
            .format('YYYY-MM-DD kk:mm:ss')
            .replace(/([ ][24]+)/g, ' 00')
          dateList = list.filter(x => new Date(Date.parse(new Date())) <= timer)
          break
        default:
          timer = Number(this.dateList[this.dateIndex])
          dateList = list.filter(x => new Date(x.invoice.datetime_close).getFullYear() === timer)
          break
      }
      // 根据时间渲染当前列表
      if (list[0] !== undefined) {
        if (viewType === 'a') {
          return dateList.filter(x => x.status !== 'paid' && x.status !== 'voided')
        }
        if (viewType === 'b') {
          return dateList.filter(x => x.status === 'paid')
        }
        if (viewType === 'c') {
          return dateList.filter(x => x.status === 'voided')
        }
      }
      return list
    }
  },
  methods: {
    // img 标签绑定的 error 事件，用于网络加载失败使用本地图片代替
    handleError(e) {
      e.currentTarget.src = './../static/img/mxbc/Ice_Cream/Ferris_Crispy.jpeg'
    },
    // 发送当前点击订单信息
    viewDetail(item) {
      this.$store.commit('viewNowDetail', item)
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 120
      })
      setTimeout(() => {
        this.$router.push({ path: '/home/detail', query: { dateIndex: this.dateIndex, activeName: this.activeName } })
      }, 120)
    }
  }
}
</script>

<style lang="less" scoped>
.order-headbox {
  position: fixed;
  max-width: 640px;
  width: 100%;
  height: 46px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #ededed;
  color: #363636;
  line-height: 46px;
  text-align: center;
  font-weight: 500;
  z-index: 2;
}
/deep/.van-tab {
  background-color: #ededed;
}
/deep/.van-tabs__nav {
  background-color: #ededed;
}
.order-menu-box {
  position: relative;
  max-width: 640px;
  width: 100%;
  left: 50%;
  transform: translateX(-50%);
  top: 46px;
  /deep/.van-tabs__line {
    background-color: orange;
  }
}
.order-data-box {
  position: relative;
  top: 46px;
  margin-bottom: 0.9em;
  /deep/.van-tabs__line {
    background-color: orange;
  }
}
.history-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  top: 46px;
  width: 100%;
  .history-content {
    width: 97%;
    height: 110px;
    border-radius: 9px;
    background-color: white;
    margin-bottom: 0.45em;
    .order-state {
      position: relative;
      left: 50%;
      transform: translate(-50%);
      display: flex;
      width: 95%;
      height: 25%;
      border-bottom: 0.06em solid #e0e0e0;
      .order-date {
        display: flex;
        align-items: center;
        width: 80%;
        height: 100%;
        span:nth-child(1) {
          font-size: 0.85em;
        }
      }
      .order-share {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        width: 20%;
        height: 100%;
        .van-icon-share-o {
          font-size: 1.2em;
          color: orange;
        }
        span:nth-child(2) {
          color: orange;
          margin-left: 0.3em;
        }
      }
    }
    .order-content {
      position: relative;
      display: flex;
      width: 75%;
      height: 75%;
      overflow-x: scroll;
      margin-left: 2.5%;
      .order-img {
        display: flex;
        align-items: center;
        height: 100%;
        .img-list {
          overflow: hidden;
          width: 60px;
          height: 60px;
          border-radius: 6px;
          margin-right: 0.6em;
          img:nth-child(1) {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
    .order-amount {
      position: absolute;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      right: 1.5%;
      bottom: 0;
      width: 20%;
      height: 75%;
      padding-right: 2.5%;
      span:nth-child(1) {
        font-size: 0.8em;
        margin-top: 0.6em;
      }
      span:nth-child(2) {
        font-size: 0.8em;
      }
    }
  }
}
.bottom-box {
  position: relative;
  top: 46px;
  height: 66px;
}
</style>
